package loadiconhandler

import (
	"gmap-backend/internal/config"
	"gmap-backend/internal/server/vo"
	"io/fs"
	"path/filepath"
	"strings"
)

const (
	SPECIAL_PATH_FOLDER  = "folder"
	SPECIAL_PATH_DIR     = "dir"
	SPECIAL_PATH_GMAP    = "gmap"
	SPECIAL_PATH_CPPATH  = "cppath"
	SPECIAL_PATH_CMD     = "cmd"
	SPECIAL_PATH_MENU    = "menu"
	SPECIAL_PATH_TXT     = "txt"
	SPECIAL_PATH_PHOTO   = "photo"
	SPECIAL_PATH_BROWSER = "browser"
)

// FindCachedIcon 从缓存目录中查找指定md5开头的文件，如果存在，则作为结果返回。该函数被subHandlers的各项调用
// 此函数只返回单一的URL，不处理图标叠加的情况，叠加的逻辑需要各subHandlers自己实现
func FindCachedIcon(appConfig *config.AppConfig, md5 string) *vo.LoadIconResp {
	cachedFile := ""
	e := filepath.WalkDir(appConfig.PathConfig.CacheDir, func(path string, d fs.DirEntry, err error) error {
		if nil != err {
			return err
		}
		if !d.IsDir() && strings.HasPrefix(d.Name(), md5) {
			cachedFile = path
			return fs.SkipAll
		}
		return nil
	})
	if nil != e {
		panic("读取图标缓存时出现错误")
	}
	if "" == cachedFile {
		return nil
	}
	resultUrl := "file:///" + strings.TrimSpace(strings.ReplaceAll(cachedFile, "\\", "/"))
	return &vo.LoadIconResp{Url: resultUrl}
}

type LoadIconSubHandler interface {
	CanHandle(appConfig *config.AppConfig, req *vo.PathReq) (bool, any)

	// 抛出panic表示处理时出错
	// 其它情况表示处理正常
	Handle(appConfig *config.AppConfig, req *vo.PathReq, extra any) *vo.LoadIconResp
}
